<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <!-- 删除字节跳动图标链接 -->
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <title>你画AI猜</title>
    <style>
        body {
            background-color: #ffffff;
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        #targetWord {
            position: fixed;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            background: #f9e6d3;
            border-radius: 25px;
            padding: 10px 20px;
            margin: 10px auto;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            z-index: 100;
        }
        .toolbox {
            position: fixed;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            width: 60px;
            background: #ffffff;
            border-radius: 12px;
            padding: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .tool-btn {
            width: 45px;
            height: 45px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
            cursor: pointer;
            transition: all 0.2s;
        }
        .tool-btn:hover {
            background: #f5f5f5;
            transform: scale(1.05);
        }
        .tool-btn.active {
            border-color: #4CAF50;
            background: #e8f5e9;
        }
        .canvas-section {
            position: relative;
            margin: 80px 20px 20px 20px;
            background: white;
            border: 2px solid #FFE4D6;
            border-radius: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            height: calc(100vh - 120px);
            overflow: hidden;
        }
        #drawingCanvas {
            width: 100%;
            height: 100%;
            cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M18.5 2.5c-1 0-2 .4-2.7 1.1L4.5 15v4.5h4.5l11.4-11.3c1.5-1.5 1.5-3.9 0-5.4-0.7-0.7-1.7-1.1-2.7-1.1zm-14 14.1l9.9-9.9 2.4 2.4-9.9 9.9h-2.4v-2.4z" fill="%23FF7F50"/></svg>') 0 24, auto;
            background: #ffffff;
            background-image:
                linear-gradient(rgba(255, 228, 214, 0.1) 1px, transparent 1px),
                linear-gradient(90deg, rgba(255, 228, 214, 0.1) 1px, transparent 1px);
            background-size: 20px 20px;
            border-radius: 15px;
        }
        #drawingCanvas.eraser-cursor {
            cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="%23FF7F50"><circle cx="12" cy="12" r="10" fill-opacity="0.2"/><circle cx="12" cy="12" r="8" fill-opacity="0.3"/></svg>') 12 12, auto;
        }
        .canvas-section:hover {
            border-color: #FFB088;
            box-shadow: 0 4px 12px rgba(255, 176, 136, 0.15);
            transition: all 0.3s ease;
        }
        .canvas-controls {
            position: fixed;
            right: 20px;
            bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .control-btn {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            border: none;
            background: #ffffff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }
        .color-picker {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .color-btn {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            border: 3px solid white;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .color-btn:hover {
            transform: scale(1.1);
        }
        .color-btn.active {
            transform: scale(1.15);
            box-shadow: 0 0 0 3px rgba(255, 176, 136, 0.5);
        }
        .chat-box {
            position: fixed;
            right: 20px;
            bottom: 20px;
            width: 400px;
            max-height: 280px;
            background: rgba(255, 255, 255, 0.98);
            border: 2px solid #FFE4D6;
            border-radius: 15px;
            padding: 15px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            overflow-y: auto;
            z-index: 1000;
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;
        }
        .chat-box .message {
            background: #fff5e6;
            border-radius: 10px;
            padding: 12px;
            margin-bottom: 10px;
            font-size: 16px;
            line-height: 1.5;
            color: #666;
        }
        .thinking-dots {
            display: flex;
            align-items: center;
            gap: 4px;
            color: #FF7F50;
            font-weight: bold;
        }
        .thinking-dots::after {
            content: '...';
            animation: thinking 1.5s infinite;
        }
        @keyframes thinking {
            0% { opacity: 0.3; }
            50% { opacity: 1; }
            100% { opacity: 0.3; }
        }
        .error-message {
            color: #ff4444;
            background: #ffe6e6;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 10px;
        }
        .chat-box::-webkit-scrollbar {
            width: 6px;
        }
        .chat-box::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        .chat-box::-webkit-scrollbar-thumb {
            background: #FFB088;
            border-radius: 3px;
        }
        .chat-box::-webkit-scrollbar-thumb:hover {
            background: #FF9F7F;
        }
        .chat-title {
            font-size: 14px;
            font-weight: bold;
            color: #FF7F50;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 1px solid #FFE4D6;
        }
        .tool-btn.active {
            background: #FFE4D6;
            color: #FF7F50;
            transform: scale(1.1);
            box-shadow: 0 0 0 3px rgba(255, 176, 136, 0.5);
        }
        .top-nav {
            width: 100%;
            padding: 20px;
            background: rgba(255, 255, 255, 0.95);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            z-index: 100;
        }
        .center-content {
            max-width: 1200px;
            width: 100%;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            flex-wrap: wrap; /* 允许元素换行 */
        }
        @media screen and (max-width: 768px) {
            .top-nav {
                padding: 10px 5px;
            }
            .center-content {
                gap: 10px;
                justify-content: space-between; /* 移动端元素两端对齐 */
                padding: 0 10px;
            }
            /* 调整子元素在移动端的布局 */
            #categorySelect {
                flex: 0 0 auto;
            }
            .word-display {
                flex: 1 1 auto;
                text-align: center;
            }
            .score-section {
                flex: 0 0 auto;
                margin-left: auto; /* 推到右侧 */
            }
            .next-btn {
                width: 100%; /* 让"下一题"按钮占满宽度 */
                margin-top: 10px;
                order: 4; /* 调整显示顺序，放到最下面 */
            }
        }
        /* 超小屏幕额外优化 */
        @media screen and (max-width: 375px) {
            .center-content {
                gap: 8px;
                padding: 0 5px;
            }
        }
        #categorySelect {
            background: linear-gradient(135deg, #FFFFFF, #FFF5EE);
            border: 2px solid #FFB088;
            border-radius: 20px;
            padding: 8px 15px;
            font-size: 16px;
            color: #FF7F50;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        #categorySelect:hover {
            background: linear-gradient(135deg, #FFF5EE, #FFE4D6);
            transform: translateY(-1px);
        }
        .word-display {
            background: linear-gradient(135deg, #FFF, #FFE4D6);
            padding: 8px 20px;
            border-radius: 20px;
            border: 2px solid #FFB088;
            color: #FF7F50;
            font-size: 16px;
            font-weight: bold;
        }
        .next-btn {
            background: linear-gradient(135deg, #FF9F7F, #FF7F50);
            color: white;
            border: none;
            border-radius: 20px;
            padding: 8px 20px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .next-btn:hover {
            background: linear-gradient(135deg, #FF7F50, #FF6B3D);
            transform: translateY(-1px);
        }
        .score-section {
            background: linear-gradient(135deg, #FFF, #FFE4D6);
            padding: 8px 15px;
            border-radius: 20px;
            border: 2px solid #FFB088;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .score-display {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .score-label {
            color: #FF7F50;
            font-weight: bold;
            font-size: 14px;
        }
        #currentScore {
            background: linear-gradient(135deg, #FFE4D6, #FFB088);
            color: white;
            padding: 4px 12px;
            border-radius: 12px;
            font-weight: bold;
            min-width: 30px;
            text-align: center;
        }
        .reset-btn {
            background: linear-gradient(135deg, #FFB088, #FF9F7F);
            color: white;
            border: none;
            border-radius: 15px;
            padding: 5px 12px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .reset-btn:hover {
            background: linear-gradient(135deg, #FF9F7F, #FF8B66);
            transform: translateY(-1px);
        }
        .drawing-tools {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.98);
            border: 2px solid #FFE4D6;
            border-radius: 30px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            backdrop-filter: blur(10px);
        }
        .divider {
            width: 1px;
            height: 25px;
            background: #eee;
            margin: 0 5px;
        }
        .tool-btn {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            border: none;
            background: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: #666;
            transition: all 0.2s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .tool-btn:hover {
            background: #f5f5f5;
            transform: translateY(-2px);
        }
        .tool-btn.active {
            background: #FFE4D6;
            color: #FF7F50;
        }
        .canvas-title {
            position: absolute;
            top: -30px;
            left: 20px;
            color: #FF7F50;
            font-size: 14px;
            font-weight: bold;
            opacity: 0.8;
        }
        .right-bottom-container {
            position: fixed;
            right: 20px;
            top: 100px;
            width: 280px;
            z-index: 1000;
        }
        .right-bottom-container::before {
            content: '';
            position: absolute;
            left: -10px;
            top: 0;
            width: 10px;
            height: 100%;
            cursor: pointer;
        }
        .right-bottom-container:hover {
            right: 10px;
        }
        .score-section {
            background: linear-gradient(135deg, #FFF, #FFE4D6);
            padding: 8px 15px;
            border-radius: 20px;
            border: 2px solid #FFB088;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .score-display {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .score-label {
            color: #FF7F50;
            font-weight: bold;
            font-size: 14px;
        }
        #currentScore {
            background: linear-gradient(135deg, #FFE4D6, #FFB088);
            color: white;
            padding: 4px 12px;
            border-radius: 12px;
            font-weight: bold;
            min-width: 30px;
            text-align: center;
        }
        .reset-btn {
            background: linear-gradient(135deg, #FFB088, #FF9F7F);
            color: white;
            border: none;
            border-radius: 15px;
            padding: 5px 12px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .reset-btn:hover {
            background: linear-gradient(135deg, #FF9F7F, #FF8B66);
            transform: translateY(-1px);
        }
        .chat-box {
            background: rgba(255, 255, 255, 0.98);
            border: 2px solid #FFE4D6;
            border-radius: 20px;
            padding: 15px;
            height: 40vh;
            overflow-y: auto;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 10px rgba(255, 156, 74, 0.15);
        }
        .chat-box:hover {
            transform: translateX(-5px);
        }
        .toggle-indicator {
            position: absolute;
            left: -25px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255, 255, 255, 0.98);
            border: 2px solid #FFE4D6;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #FF7F50;
            font-size: 12px;
            box-shadow: 0 2px 10px rgba(255, 156, 74, 0.15);
        }
        .chat-title {
            font-size: 14px;
            font-weight: bold;
            color: #FF7F50;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 1px solid #FFE4D6;
        }
        .message {
            background: #fff5e6;
            border-radius: 10px;
            padding: 12px;
            margin-bottom: 10px;
            font-size: 16px;
            line-height: 1.5;
            color: #666;
            position: relative;
        }
        .answer-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            justify-content: flex-end;
        }
        .answer-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 15px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        .correct-btn {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
        }
        .wrong-btn {
            background: linear-gradient(135deg, #ff4444, #cc0000);
            color: white;
        }
        .answer-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .eraser-sizes {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 10px;
        }
        .eraser-sizes::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 5px solid white;
        }
        .eraser-size-btn {
            display: block;
            width: 100%;
            padding: 6px 12px;
            margin: 4px 0;
            border: none;
            border-radius: 4px;
            background: #f5f5f5;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
        }
        .eraser-size-btn:hover {
            background: #e0e0e0;
        }
        .decorative-icons {
            position: absolute;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 0;
        }

        .icon {
            position: absolute;
            font-size: 20px;
            opacity: 0.3;
            animation: float 3s ease-in-out infinite;
        }

        /* 调整图标位置，使其分布在 top-nav 区域 */
        .icon-1 { top: 10px; left: 5%; }
        .icon-2 { top: 30px; left: 15%; }
        .icon-3 { top: 15px; right: 5%; }
        .icon-4 { top: 25px; right: 15%; }
        .icon-5 { top: 20px; left: 25%; }
        .icon-6 { top: 10px; right: 25%; }
        .icon-7 { top: 30px; left: 35%; }
        .icon-8 { top: 15px; right: 35%; }

        @keyframes float {
            0% {
                transform: translateY(0) rotate(0deg);
            }
            50% {
                transform: translateY(-5px) rotate(5deg);
            }
            100% {
                transform: translateY(0) rotate(0deg);
            }
        }

        /* 确保中心内容在图标上层 */
        .center-content {
            position: relative;
            z-index: 1;
        }

        /* 添加弹窗样式 */
        .word-popup {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.5);
            background: rgba(255, 255, 255, 0.95);
            padding: 40px 80px;
            border-radius: 20px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            text-align: center;
        }

        .word-popup.show {
            transform: translate(-50%, -50%) scale(1);
            opacity: 1;
            visibility: visible;
        }

        .word-popup .title {
            font-size: 24px;
            color: #666;
            margin-bottom: 15px;
        }

        .word-popup .word {
            font-size: 48px;
            font-weight: bold;
            color: #ff7f27;
            margin: 20px 0;
        }

        /* 添加响应式样式 */
        @media screen and (max-width: 768px) {
            /* 顶部导航栏优化 */
            .top-nav {
                padding: 10px 5px;
            }

            /* 下拉框样式优化 */
            #categorySelect {
                font-size: 14px;
                padding: 6px 10px;
                min-width: 60px;
                height: 32px;
            }

            /* 分数显示优化 */
            .score-display {
                font-size: 14px;
                padding: 4px 10px;
            }

            .score-label {
                font-size: 12px;
            }

            #currentScore {
                padding: 2px 8px;
                min-width: 24px;
                font-size: 14px;
            }

            .reset-btn {
                font-size: 12px;
                padding: 4px 8px;
            }

            /* 当前词语显示 */
            .word-display {
                font-size: 14px;
                padding: 6px 12px;
            }

            /* 下一题按钮 */
            .next-btn {
                font-size: 14px;
                padding: 6px 15px;
            }

            /* 弹窗进一步优化 */
            .word-popup {
                width: 80%;
                padding: 20px;
            }

            .word-popup .title {
                font-size: 18px;
                margin-bottom: 15px;
            }

            .word-popup .word {
                font-size: 32px;
                margin: 15px 0;
            }
        }

        /* 针对超小屏幕的额外调整 */
        @media screen and (max-width: 375px) {
            .word-popup {
                width: 90%;
                padding: 20px;
            }

            .word-popup .word {
                font-size: 32px;
            }

            .tool-btn {
                padding: 6px;
            }

            .color-btn {
                width: 25px;
                height: 25px;
            }
        }

        /* 聊天框优化 */
        .chat-box {
            margin: 5px;
            border-radius: 12px;
            padding: 10px;
            height: 150px;  /* 减小高度 */
            width: 300px;   /* 减小宽度 */
        }

        .chat-title {
            font-size: 14px;
            padding: 5px 10px;
            margin-bottom: 5px;
        }

        .message {
            font-size: 14px;
            padding: 8px;
            line-height: 1.3;
        }

        /* 底部工具栏优化 */
        .drawing-tools {
            padding: 8px;
            gap: 8px;
            border-radius: 15px;
            bottom: 10px;  /* 调整位置 */
        }

        /* 颜色按钮优化 */
        .color-btn {
            width: 25px;
            height: 25px;
        }

        /* 工具按钮优化 */
        .tool-btn {
            font-size: 18px;
            padding: 6px;
            min-width: 32px;
            height: 32px;
        }

        .divider {
            height: 20px;
            margin: 0 3px;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
    <!-- 添加装饰图标 -->
    <div class="decorative-icons">
        <div class="icon icon-1">🎨</div>
        <div class="icon icon-2">✏️</div>
        <div class="icon icon-3">🖼️</div>
        <div class="icon icon-4">🎯</div>
        <div class="icon icon-5">🎮</div>
        <div class="icon icon-6">🎪</div>
        <div class="icon icon-7">🖌️</div>
        <div class="icon icon-8">🎭</div>
    </div>

    <div class="top-nav">
        <div class="center-content">
            <select id="categorySelect" onchange="handleCategoryChange()">
                <option value="animals">动物</option>
                <option value="objects">物品</option>
                <option value="idioms">成语</option>
                <option value="food">食物</option>
                <option value="sports">运动</option>
            </select>
            <div class="word-display">
                <span id="currentWord">猫</span>
            </div>
            <button class="next-btn" onclick="generateNewWord()">下一题</button>
            <div class="score-section">
                <div class="score-display">
                    <span class="score-label">积分</span>
                    <span id="currentScore">0</span>
                </div>
                <button class="reset-btn" onclick="resetScore()">重置</button>
            </div>
        </div>
    </div>

    <!-- 右侧只保留对话框 -->
    <div class="right-bottom-container">
        <div class="chat-box" id="recognition">
            <div class="chat-title">小豆包</div>
            <div class="message">
                <div class="markdown-content">让我猜猜...</div>
            </div>
        </div>
    </div>
    <div class="drawing-tools">
        <div class="color-picker">
            <div class="color-btn active" data-color="#000000" style="background-color: #000000" onclick="setColor('#000000')"></div>
            <div class="color-btn" data-color="#ff0000" style="background-color: #ff0000" onclick="setColor('#ff0000')"></div>
            <div class="color-btn" data-color="#00ff00" style="background-color: #00ff00" onclick="setColor('#00ff00')"></div>
            <div class="color-btn" data-color="#0000ff" style="background-color: #0000ff" onclick="setColor('#0000ff')"></div>
        </div>
        <div class="divider"></div>
        <button class="tool-btn" id="eraser" onclick="setEraser()" title="橡皮擦">🧽</button>
        <button class="tool-btn" onclick="undo()" title="撤销">↩️</button>
        <button class="tool-btn" onclick="clearCanvas()" title="清空">🗑️</button>
    </div>
    <div class="canvas-section">
        <div class="canvas-title">绘画区域</div>
        <canvas id="drawingCanvas"></canvas>
    </div>

    <!-- 添加弹窗HTML -->
    <div id="wordPopup" class="word-popup">
        <div class="word" id="popupWord"></div>
    </div>

    <script>
        const canvas = document.getElementById('drawingCanvas');
        const ctx = canvas.getContext('2d');

        // 设置画布尺寸
        function resizeCanvas() {
            const container = canvas.parentElement;
            canvas.width = container.clientWidth;
            canvas.height = container.clientHeight;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.strokeStyle = '#000000';
            ctx.lineWidth = 3;
        }

        // 绘画状态变量
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;
        let recognitionTimer = null; // 新增：识别定时器

        // 绘画事件处理
        function startDrawing(e) {
            isDrawing = true;
            // 如果开始新的绘画，清除识别定时器
            if (recognitionTimer) {
                clearTimeout(recognitionTimer);
                recognitionTimer = null;
            }

            const rect = canvas.getBoundingClientRect();
            [lastX, lastY] = [
                e.clientX - rect.left,
                e.clientY - rect.top
            ];
        }

        function draw(e) {
            if (!isDrawing) return;

            const rect = canvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();

            [lastX, lastY] = [x, y];
        }

        function stopDrawing() {
            if (isDrawing) {
                isDrawing = false;
                saveDrawingState();

                // 清除之前的定时器
                if (recognitionTimer) {
                    clearTimeout(recognitionTimer);
                }

                // 设置新的定时器，3秒后触发识别
                recognitionTimer = setTimeout(() => {
                    // 检查3秒内是否有新的绘画
                    if (!isDrawing) {
                        console.log('3秒内没有新的绘画，开始识别...');
                        sendToRecognition();
                    }
                }, 3000);
            }
        }

        // 绑定画布事件
        function initializeCanvas() {
            canvas.addEventListener('mousedown', startDrawing);
            canvas.addEventListener('mousemove', draw);
            canvas.addEventListener('mouseup', stopDrawing);
            canvas.addEventListener('mouseout', stopDrawing);

            // 触摸设备支持
            canvas.addEventListener('touchstart', (e) => {
                e.preventDefault();
                const touch = e.touches[0];
                const mouseEvent = new MouseEvent('mousedown', {
                    clientX: touch.clientX,
                    clientY: touch.clientY
                });
                canvas.dispatchEvent(mouseEvent);
            });

            canvas.addEventListener('touchmove', (e) => {
                e.preventDefault();
                const touch = e.touches[0];
                const mouseEvent = new MouseEvent('mousemove', {
                    clientX: touch.clientX,
                    clientY: touch.clientY
                });
                canvas.dispatchEvent(mouseEvent);
            });

            canvas.addEventListener('touchend', (e) => {
                e.preventDefault();
                const mouseEvent = new MouseEvent('mouseup', {});
                canvas.dispatchEvent(mouseEvent);
            });
        }

        // 初始化时调用
        window.onload = function() {
            resizeCanvas();
            initializeCanvas();
            window.addEventListener('resize', resizeCanvas);

            // 初始保存空白状态
            saveDrawingState();

            // 初始化分数显示
            document.getElementById('currentScore').textContent = '0';
        }

        // 工具选择状态管理
        let currentTool = 'pen'; // 默认使用画笔

        // 更新工具选择状态
        function updateToolState(toolType) {
            currentTool = toolType;
            // 移除所有工具按钮的active状态
            document.querySelectorAll('.tool-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelectorAll('.color-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            // 根据当前工具设置active状态
            if (toolType === 'pen') {
                const currentColor = ctx.strokeStyle;
                document.querySelector(`.color-btn[data-color="${currentColor}"]`)?.classList.add('active');
            } else if (toolType === 'eraser') {
                document.querySelector('.tool-btn[data-tool="eraser"]').classList.add('active');
            }
        }

        // 设置颜色
        function setColor(color) {
            currentTool = 'pen';
            ctx.globalCompositeOperation = 'source-over';
            ctx.strokeStyle = color;
            ctx.lineWidth = 3; // 恢复画笔默认大小

            // 更新颜色按钮状态
            document.querySelectorAll('.color-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector(`.color-btn[data-color="${color}"]`).classList.add('active');
            canvas.classList.remove('eraser-cursor'); // 移除橡皮擦光标样式
        }

        // 设置橡皮擦
        function setEraser() {
            currentTool = 'eraser';
            ctx.globalCompositeOperation = 'destination-out';
            ctx.lineWidth = 20;
            canvas.classList.add('eraser-cursor'); // 添加橡皮擦光标样式

            // 更新工具按钮状态
            document.querySelectorAll('.tool-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.getElementById('eraser').classList.add('active');
        }

        // 清空画布
        function clearCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }

        // 设置画笔
        function setDrawingTool() {
            ctx.globalCompositeOperation = 'source-over';
            ctx.strokeStyle = document.querySelector('.color-btn.active')?.style.backgroundColor || '#000000';
        }

        // 添加历史记录数组
        let drawingHistory = [];
        let currentStep = -1;

        // 保存绘画状态
        function saveDrawingState() {
            currentStep++;
            // 删除当前步骤之后的所有历史记录
            drawingHistory = drawingHistory.slice(0, currentStep);
            // 保存当前画布状态
            drawingHistory.push(canvas.toDataURL());
        }

        // 撤销功能
        function undo() {
            if (currentStep > 0) {
                currentStep--;
                restoreDrawingState();
            }
        }

        // 恢复绘画状态
        function restoreDrawingState() {
            const img = new Image();
            img.src = drawingHistory[currentStep];
            img.onload = function() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0);
            }
        }

        // 修改防抖函数的延迟时间
        const debounceRecognize = (() => {
            let timeout;
            return () => {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    console.log('触发识别...');
                    sendToRecognition();
                }, 2000); // 增加到2秒的延迟
            };
        })();

        // 图片识别功能优化
        async function sendToRecognition() {
            try {
                console.log('开始识别过程...');
                const recognitionDiv = document.getElementById('recognition');
                recognitionDiv.innerHTML = `
                    <div class="chat-title">小豆包</div>
                    <div class="message">
                        <div class="thinking-dots">思考中...</div>
                    </div>
                `;

                const imageData = canvas.toDataURL('image/png');
                const blob = await fetch(imageData).then(res => res.blob());

                const formData = new FormData();
                formData.append('file', blob, 'drawing.png');

                const categorySelect = document.getElementById('categorySelect');
                const selectedCategory = categorySelect.options[categorySelect.selectedIndex].text;

                console.log('上传图片...');
                const uploadResponse = await fetch('https://api.coze.cn/v1/files/upload', {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer pat_MbcNnALP1qXQtgIvIIQ3YoshlGpcwVHk8EnjANU4jfWpF3ZgHeyvM6jdB4zmpNOa'
                    },
                    body: formData
                });

                if (!uploadResponse.ok) {
                    throw new Error('文件上传失败');
                }

                const uploadResult = await uploadResponse.json();
                console.log('文件上传成功:', uploadResult);

                const fileId = uploadResult.data.id;
                await runWorkflowWithFileId(fileId, selectedCategory);

            } catch (error) {
                console.error('识别过程出错:', error);
                const recognitionDiv = document.getElementById('recognition');
                recognitionDiv.innerHTML = `
                    <div class="error-message">
                        识别失败，请稍后重试
                    </div>
                `;
            }
        }

        // 工作流执行函数优化
        async function runWorkflowWithFileId(fileId, kind) {
            console.log('执行工作流...', {fileId, kind});

            const apiUrl = 'https://api.coze.cn/v1/workflow/stream_run';
            const headers = {
                'Authorization': 'Bearer pat_MbcNnALP1qXQtgIvIIQ3YoshlGpcwVHk8EnjANU4jfWpF3ZgHeyvM6jdB4zmpNOa',
                'Content-Type': 'application/json'
            };

            const requestBody = {
                workflow_id: '7455698144098369571',
                parameters: {
                    image: {
                        file_id: fileId
                    },
                    kind: kind
                }
            };

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                console.log('开始接收响应数据');

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let result = '';

                while (true) {
                    const {done, value} = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, {stream: true});
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';

                    for (const line of lines) {
                        if (!line.trim()) continue;

                        if (line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.slice(6);
                                if (jsonStr.trim() === '[DONE]') continue;

                                const data = JSON.parse(jsonStr);
                                console.log('收到数据:', data);

                                if (data.content_type === 'text' && data.content) {
                                    result += data.content;
                                    updateRecognitionResult(result);
                                }
                            } catch (e) {
                                console.error('解析数据失败:', e);
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('工作流执行错误:', error);
                updateRecognitionResult('识别失败，请重试');
            }
        }

        // 更新识别结果显示
        function updateRecognitionResult(content) {
            const recognitionDiv = document.getElementById('recognition');
            recognitionDiv.innerHTML = `
                <div class="chat-title">
                    小豆包
                    <button class="speak-btn" onclick="speakText('${content.replace(/'/g, "\\'")}')">
                        🔊
                    </button>
                </div>
                <div class="message">
                    <div class="markdown-content">
                        ${marked.parse(content)}
                    </div>
                    <div class="answer-buttons">
                        <button class="answer-btn correct-btn" onclick="handleAnswer(true)">✓ 正确</button>
                        <button class="answer-btn wrong-btn" onclick="handleAnswer(false)">✗ 错误</button>
                    </div>
                </div>
            `;
            recognitionDiv.scrollTop = recognitionDiv.scrollHeight;

            // 自动播放识别结果
            speakText(content);
        }

        // 添加语音按钮样式
        const style = document.createElement('style');
        style.textContent = `
            .speak-btn {
                background: none;
                border: none;
                cursor: pointer;
                font-size: 16px;
                padding: 4px 8px;
                border-radius: 4px;
                transition: all 0.2s ease;
                margin-left: 8px;
            }

            .speak-btn:hover {
                background: rgba(255, 127, 80, 0.1);
            }

            .chat-title {
                display: flex;
                align-items: center;
            }
        `;
        document.head.appendChild(style);

        // 添加语音朗读功能
        function speakText(text) {
            // 检查浏览器是否支持语音合成
            if ('speechSynthesis' in window) {
                // 创建语音合成实例
                const utterance = new SpeechSynthesisUtterance();

                // 设置语音参数
                utterance.text = text;
                utterance.lang = 'zh-CN';  // 设置为中文
                utterance.volume = 1;  // 音量 0-1
                utterance.rate = 1;    // 语速 0.1-10
                utterance.pitch = 1;   // 音高 0-2

                // 播放语音
                window.speechSynthesis.speak(utterance);
            }
        }

        // 添加词库
        const wordLibrary = {
            animals: [
                '猫', '狗', '兔子', '大象', '长颈鹿', '熊猫', '老虎', '狮子', '猴子', '鹦鹉',
                '企鹅', '斑马', '河马', '袋鼠', '浣熊', '松鼠', '考拉', '蝴蝶', '青蛙', '鳄鱼',
                '海豚', '章鱼', '孔雀', '羊驼', '刺猬', '北极熊', '小鸡', '蜗牛', '金鱼', '小鸭',
                '蜘蛛', '蚂蚁', '蜜蜂', '螃蟹', '海马', '海狮', '犀牛', '山羊', '绵羊', '骆驼',
                '仓鼠', '豪猪', '蝙蝠', '鸵鸟', '天鹅', '鸽子', '猫头鹰', '蛇', '蜥蜴', '树懒'
            ],
            objects: [
                '椅子', '手机', '电脑', '书本', '眼镜', '钥匙', '雨伞', '手表', '水杯', '铅笔',
                '电视', '冰箱', '微波炉', '床', '沙发', '台灯', '背包', '相机', '耳机', '鞋子',
                '帽子', '剪刀', '尺子', '篮球', '足球', '吉他', '钢琴', '花瓶', '垃圾桶', '门',
                '窗户', '马桶', '浴缸', '洗衣机', '空调', '电风扇', '路由器', '充电器', '打印机', '键盘',
                '鼠标', '书架', '衣柜', '镜子', '枕头', '毛巾', '牙刷', '梳子', '雨靴', '遥控器'
            ],
            idioms: [
                '画蛇添足', '对牛弹琴', '守株待兔', '掩耳盗铃', '盲人摸象', '井底之蛙', '画龙点睛', '一箭双雕', '狐假虎威', '亡羊补牢',
                '杯弓蛇影', '草木皆兵', '叶公好龙', '塞翁失马', '愚公移山', '胸有成竹', '望梅止渴', '蜻蜓点水', '螳臂当车', '惊弓之鸟',
                '鹤立鸡群', '鸟语花香', '龙飞凤舞', '虎头蛇尾', '鱼目混珠', '狼吞虎咽', '蚂蚁搬家', '鸡飞狗跳', '龙腾虎跃', '鹬蚌相争',
                '画地为牢', '如鱼得水', '风驰电掣', '风雨同舟', '守望相助', '破釜沉舟', '顺手牵羊', '一鸣惊人', '鸡鸣狗盗', '鹏程万里',
                '蛛丝马迹', '鸟尽弓藏', '虎视眈眈', '龙马精神', '鸟飞兔走', '蜂拥而至', '鱼跃龙门', '鸟入樊笼', '蛇行鼠窜', '鹰击长空'
            ],
            food: [
                '火锅', '寿司', '汉堡', '披萨', '饺子', '面条', '蛋糕', '冰淇淋', '巧克力', '薯条',
                '包子', '春卷', '炒饭', '烤肉', '三明治', '水饺', '拉面', '麻辣烫', '烤鸭', '糖醋里脊',
                '牛排', '意大利面', '煎饼', '小笼包', '蛋挞', '奶茶', '咖啡', '可乐', '果汁', '啤酒',
                '苹果', '香蕉', '西瓜', '草莓', '葡萄', '橙子', '柠檬', '菠萝', '樱桃', '芒果',
                '烧烤', '粽子', '月饼', '汤圆', '馄饨', '炸鸡', '热狗', '寿司', '泡面', '蛋炒饭'
            ],
            sports: [
                '足球', '篮球', '排球', '网球', '乒乓球', '羽毛球', '高尔夫', '棒球', '橄榄球', '冰球',
                '滑冰', '滑雪', '游泳', '跑步', '跳远', '举重', '体操', '武术', '跆拳道', '柔道',
                '马拉松', '自行车', '攀岩', '冲浪', '滑板', '瑜伽', '太极拳', '射箭', '击剑', '拳击',
                '跳绳', '健身', '舞蹈', '空手道', '散步', '划船', '帆船', '潜水', '跳伞', '骑马',
                '轮滑', '飞盘', '台球', '保龄球', '壁球', '曲棍球', '垒球', '沙滩排球', '铁人三项', '跑酷'
            ]
        };

        // 生成新词函数
        function generateNewWord() {
            const category = document.getElementById('categorySelect').value;
            const words = wordLibrary[category];
            const randomIndex = Math.floor(Math.random() * words.length);
            const newWord = words[randomIndex];

            // 更新弹窗内容
            document.getElementById('popupWord').textContent = newWord;

            // 显示弹窗
            const popup = document.getElementById('wordPopup');
            popup.classList.add('show');
            document.getElementById('currentWord').textContent = newWord;
            // 1.5秒后隐藏弹窗并更新词语
            setTimeout(() => {
                popup.classList.remove('show');
            }, 2000);

            // 清空画布
            clearCanvas();

            // 重置识别框
            const recognitionDiv = document.getElementById('recognition');
            recognitionDiv.innerHTML = `
                <div class="chat-title">小豆包</div>
                <div class="message">
                    <div class="markdown-content">让我猜猜...</div>
                </div>
            `;
        }

        // 初始化分数
        let score = 0;

        // 更新分数函数
        function updateScore(isCorrect) {
            if (isCorrect) {
                score += 5;
                showScoreAnimation('+5');
            }
            document.getElementById('currentScore').textContent = score;
        }

        // 添加重置分数函数
        function resetScore() {
            score = 0;
            document.getElementById('currentScore').textContent = score;
            clearCanvas();
            showScoreAnimation('已重置');
        }

        // 显示分数动画
        function showScoreAnimation(text) {
            const animation = document.createElement('div');
            animation.textContent = text;
            animation.style.cssText = `
                position: fixed;
                color: #4CAF50;
                font-size: 24px;
                font-weight: bold;
                pointer-events: none;
                animation: floatUp 1s ease-out forwards;
            `;

            // 获取点击按钮的位置
            const rect = event.target.getBoundingClientRect();
            animation.style.left = rect.left + 'px';
            animation.style.top = rect.top + 'px';

            document.body.appendChild(animation);

            // 添加动画样式
            const style = document.createElement('style');
            style.textContent = `
                @keyframes floatUp {
                    0% {
                        transform: translateY(0);
                        opacity: 1;
                    }
                    100% {
                        transform: translateY(-50px);
                        opacity: 0;
                    }
                }
            `;
            document.head.appendChild(style);

            // 动画结束后移除元素
            setTimeout(() => {
                animation.remove();
                style.remove();
            }, 1000);
        }

        // 页面加载时初始化积分显示
        window.addEventListener('load', function() {
            resizeCanvas();
            initializeCanvas();
            window.addEventListener('resize', resizeCanvas);

            // 初始保存空白状态
            saveDrawingState();

            // 初始化分数显示
            document.getElementById('currentScore').textContent = '0';
        });

        // 处理答对时的逻辑
        function handleCorrectAnswer() {
            updateScore(true);      // 更新分数
            generateNewWord();      // 生成新题目
        }

        // 添加分类切换处理函数
        function handleCategoryChange() {
            generateNewWord();  // 生成新词
            clearCanvas();      // 清空画布

            // 重置聊天框
            const recognitionDiv = document.getElementById('recognition');
            recognitionDiv.innerHTML = `
                <div class="chat-title">小豆包</div>
                <div class="message">
                    <div class="markdown-content">让我猜猜...</div>
                </div>
            `;
        }

        // 添加处理答案的函数
        function handleAnswer(isCorrect) {
            if (isCorrect) {
                updateScore(true);
                generateNewWord();  // 这里会触发新的弹窗
            } else {
                const recognitionDiv = document.getElementById('recognition');
                recognitionDiv.innerHTML = `
                    <div class="chat-title">小豆包</div>
                    <div class="message">
                        <div class="markdown-content">让我再猜猜...</div>
                    </div>
                `;
            }
        }

        function toggleEraserSizes() {
            const eraserSizes = document.getElementById('eraserSizes');
            eraserSizes.style.display = eraserSizes.style.display === 'none' ? 'block' : 'none';

            // 切换到橡皮擦模式
            currentTool = 'eraser';
            ctx.globalCompositeOperation = 'destination-out';
        }

        function setEraserSize(size) {
            ctx.lineWidth = size;
            document.getElementById('eraserSizes').style.display = 'none';
        }

        // 点击画布其他地方时隐藏尺寸选择
        canvas.addEventListener('click', function() {
            document.getElementById('eraserSizes').style.display = 'none';
        });

        // 在原有的工具切换函数中添加处理
        function switchTool(tool) {
            currentTool = tool;
            if (tool === 'brush') {
                ctx.globalCompositeOperation = 'source-over';
                // 隐藏橡皮擦尺寸选择
                document.getElementById('eraserSizes').style.display = 'none';
            }
        }
    </script>
</body>
</html>
